package com.situ.skymall.user.api.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.model.User;
import com.situ.service.UserService;
import com.situ.skymall.user.api.service.ImageFeignService;
import com.situ.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/v1/user")
public class UserController {

    private static UserService userService;
    private final ImageFeignService imageFeignService;

    @Autowired
    public UserController(ImageFeignService imageFeignService) {
        this.imageFeignService = imageFeignService;
    }

    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    /**
     * 查询所有用户
     */
    @GetMapping("/findAll")
    public JsonResult<?> findAll(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) Integer roleType) {  // 添加roleType参数

        // 构建查询条件对象
        User search = new User();
        if (StringUtils.hasText(username)) {
            search.setUsername(username);
        }
        if (StringUtils.hasText(phone)) {
            search.setPhone(phone);
        }
        if (roleType != null) {
            search.setRoleType(roleType);
        }

        Page<User> page = userService.findAll(pageNum, pageSize, search);
        return JsonResult.success(page);
    }


    /**
     * 根据用户id查询用户
     */
    @GetMapping("/findById/{id}")
    public JsonResult<?> findById(@PathVariable Integer id) {
        try {
            User user = userService.getById(id);
            if (user == null) {
                return JsonResult.fail("用户不存在");
            }
            return JsonResult.success(user);
        } catch (Exception e) {
            return JsonResult.fail(500, "查询用户失败");
        }
    }


    /**
     * 根据用户名查询用户
     */
    @GetMapping("/findByUsername/{username}")
    public JsonResult<?> findByUsername(@PathVariable String username) {
        try {
            User user = userService.findByUsername(username);
            if (user == null) {
                return JsonResult.fail("用户不存在");
            }
            return JsonResult.success(user);
        } catch (Exception e) {
            return JsonResult.fail(500, "查询用户失败");
        }
    }

    /**
     * 修改用户状态
     */
    @PutMapping("/status/{id}/{status}")
    public JsonResult<?> updateStatus(@PathVariable Integer id, @PathVariable Integer status) {
        try {
            // 检查用户是否存在
            User user = userService.getById(id);
            if (user == null) {
                return JsonResult.fail("用户不存在");
            }

            boolean result = userService.updateStatus(id, status);
            if (result) {
                return JsonResult.success("状态更新成功");
            } else {
                return JsonResult.fail("状态更新失败");
            }
        } catch (Exception e) {
            return JsonResult.fail(500, "状态更新过程中发生错误");
        }
    }

    //添加用户
    @PostMapping("/add")
    public JsonResult<?> addUser(@RequestBody User user) {
        try {
            boolean result = userService.save(user);
            if (result) {
                return JsonResult.success("用户添加成功");
            } else {
                return JsonResult.fail("用户添加失败");
            }
        } catch (Exception e) {
            return JsonResult.fail(500, "用户添加过程中发生错误");
        }
    }

    /**
     * 修改用户角色
     */
    @PutMapping("/role/{id}/{roleType}")
    public JsonResult<?> updateRoleType(@PathVariable Integer id, @PathVariable Integer roleType) {
        try {
            // 检查用户是否存在
            User user = userService.getById(id);
            if (user == null) {
                return JsonResult.fail("用户不存在");
            }

            boolean result = userService.updateRoleType(id, roleType);
            if (result) {
                return JsonResult.success("角色更新成功");
            } else {
                return JsonResult.fail("角色更新失败");
            }
        } catch (Exception e) {
            return JsonResult.fail(500, "角色更新过程中发生错误");
        }
    }
    /**
     * 用户信息更新
     */
    @PutMapping("/update")
    public JsonResult<?> update(@RequestBody User user) {
        try {
            // 检查用户是否存在
            User existUser = userService.getById(user.getId());
            if (existUser == null) {
                return JsonResult.fail("用户不存在");
            }

            boolean result = userService.updateById(user);
            if (result) {
                return JsonResult.success("用户信息更新成功");
            } else {
                return JsonResult.fail("用户信息更新失败");
            }
        } catch (Exception e) {
            return JsonResult.fail(500, "用户信息更新过程中发生错误");
        }
    }

    /**
     * 用户信息删除
     */
    @DeleteMapping("/delete/{id}")
    public JsonResult<?> deleteUser(@PathVariable Integer id) {
        try {
            // 检查用户是否存在
            User user = userService.getById(id);
            if (user == null) {
                return JsonResult.fail("用户不存在");
            }

            boolean result = userService.deleteUser(id);
            if (result) {
                return JsonResult.success("用户删除成功");
            } else {
                return JsonResult.fail("用户删除失败");
            }
        } catch (Exception e) {
            return JsonResult.fail(500, "用户删除过程中发生错误");
        }
    }

    /**
     * 用户头像上传
     */
    @PostMapping("/avatar")
    public JsonResult<?> uploadAvatar(MultipartFile file) {
        try {
            if (file == null || file.isEmpty()) {
                return JsonResult.fail("文件不能为空");
            }

            // 通过 Feign 客户端调用 image-api
            ResponseEntity<JsonResult<String>> response = imageFeignService.upload(file);

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null && response.getBody().isSuccess()) {
                return JsonResult.success(response.getBody().getData());
            } else {
                return JsonResult.fail("头像上传失败");
            }
        } catch (Exception e) {
            // 记录日志 e.printStackTrace();
            return JsonResult.fail("头像上传过程中发生错误");
        }
    }
}
